package com.iqilu.ksd.activity.live;

import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.czt.mp3recorder.MP3Recorder;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.BaseActivity;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.FileUtils;
import com.iqilu.ksd.utils.KeyboardUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/24.
 */

public class VoiceActivity extends BaseActivity implements MediaPlayer.OnPreparedListener{

    private static final String TAG = "VoiceActivity";

    private ProgressDialog progressDialog;
    private int id;
    private MediaPlayer mediaPlayer;
    //录音相关
    private MP3Recorder mRecorder;
    private String voiceName;
    private long duration;
    private long lastSpeakTime = 0; //两次语音间隔太短可能会崩溃

    private Button btCancel;
    private Button btSend;
    private EditText etEmoji;
    private RelativeLayout layVoice;
    private ImageView btStart;
    private Chronometer chrTime;
    private ImageView btPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_view_common);
        initView();
        id = getIntent().getIntExtra("id", 0);
        layVoice.setVisibility(View.VISIBLE);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.i(TAG, "onCompletion...");
                btPlay.setImageResource(R.drawable.bt_voice_play);
            }
        });
    }

    private void initView(){
        btCancel = getView(R.id.bt_cancel);
        btSend = getView(R.id.bt_send);
        etEmoji = getView(R.id.et_emoji);
        layVoice = getView(R.id.lay_voice);
        btStart = getView(R.id.bt_start);
        btPlay = getView(R.id.bt_play);
        chrTime = getView(R.id.chr_time);
        btPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toPlay();
            }
        });
        btStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toStart();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
    }

    private void save() {
        if (mRecorder != null && mRecorder.isRecording()) {
            showStopDelDialog();
        } else {
            uploadVoice();
        }
    }

    private void uploadVoice() {
        if (duration >= 1000) {
            addVoice();
        } else {
            Toast.makeText(this, R.string.live_audio_short, Toast.LENGTH_SHORT).show();
        }
    }

    private void toStart() {
        if (mRecorder != null && mRecorder.isRecording()) {
            stopVoicce();
        } else {
            if (TextUtils.isEmpty(voiceName)) {
                startVoice();
            } else {
                showDelDialog();
            }
        }
    }

    private void toPlay() {
        if (mediaPlayer.isPlaying()) {
            stopPlay();
        } else {
            startPlay();
        }
    }

    public void showDelDialog() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.live_voice_record))
                .btnText(getString(R.string.cancel), getString(R.string.ensure))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        startVoice();
                        dialog.dismiss();
                    }
                }
        );
    }

    public void showStopDelDialog() {
        final MaterialDialog dialog = new MaterialDialog(this);
        dialog.content(getString(R.string.live_voice_recording))
                .btnText(getString(R.string.cancel), getString(R.string.ensure))
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        stopVoicce();
                        uploadVoice();
                        dialog.dismiss();
                    }
                }
        );
    }

    private void startVoice() {
        if (System.currentTimeMillis() - lastSpeakTime < 1000) return;
        if (mediaPlayer.isPlaying()) {
            stopPlay();
        }
        duration = 0;
        chrTime.setBase(SystemClock.elapsedRealtime());
        chrTime.start();
        voiceName = System.currentTimeMillis() + ".mp3";
        mRecorder = new MP3Recorder(new File(CacheUtils.getVoiceDir(this), voiceName));
        try {
            mRecorder.start();
            btStart.setImageResource(R.drawable.bt_voice_end);
            lastSpeakTime = System.currentTimeMillis();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        btPlay.setVisibility(View.GONE);
    }

    private void stopVoicce() {
        mRecorder.stop();
        chrTime.stop();
        btStart.setImageResource(R.drawable.bt_voice_start);
        duration = SystemClock.elapsedRealtime() - chrTime.getBase();
        if (duration < 1000) {
            Toast.makeText(this, R.string.live_audio_short, Toast.LENGTH_SHORT).show();
        }
        btPlay.setVisibility(View.VISIBLE);
    }

    private void startPlay() {
        String path = CacheUtils.getVoiceDir(this) + voiceName;
        if (FileUtils.isFileExists(path)) {
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepareAsync();
                btPlay.setImageResource(R.drawable.bt_voice_stop);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopPlay() {
        mediaPlayer.stop();
        mediaPlayer.reset();
        btPlay.setImageResource(R.drawable.bt_voice_play);

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mediaPlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            stopPlay();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        if (mRecorder != null && mRecorder.isRecording()) {
            stopVoicce();
        }
    }

    private void addVoice() {
        String url = Api.URL_LIVE_AUDIO;
        String audioPath = CacheUtils.getVoiceDir(this) + voiceName;
        File file = new File(audioPath);
        int mDuration = (int) duration / 1000;
        String description = Uri.encode(etEmoji.getText().toString());
        OkHttpUtils
                .post()
                .url(url)
                .addParams("liveid", "" + id)
                .addParams("description", "" + description)
                .addParams("duration", "" + mDuration)
                .addFile("filedata", "" + file.getName(), file)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        progressDialog = ProgressDialog.show(VoiceActivity.this, "", getResources().getString(R.string.live_upload_audio), true, false);
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressDialog.dismiss();
                        Toast.makeText(VoiceActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressDialog.dismiss();
                        int result = 0;
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            result = jsonObject.getInt("status");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (result == 1) {
                            Toast.makeText(VoiceActivity.this, R.string.live_addvideo_success, Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(VoiceActivity.this, R.string.live_addvideo_fail, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}
